<?php
class Frontend_Router
{
	 const CACHE_KEY_ROUTES = 'Frontend_Router_routes';
	 static protected $instance = null;
	 static protected $_moduleRoutes = null;
	 /**
	  * @var Request
	  */
	 protected $_request;
	 protected $_pageCode;
	 protected $_pageId;
	 protected $_pageData;
	 /**
	  * @return Frontend_Router
	  */
	 static public function getInstance(){
	 	if(is_null(self::$instance))
	 		self::$instance = new self;
	 	return self::$instance;	
	 }
	 protected function __clone(){}
	 protected function __construct(){
	 	$this->_request = Request::getInstance();
	 }
	 
	 public function route()
	 {
	 	$pageCode = $this->_request->getPath(0);
	 	
	 	if(!strlen($pageCode))
	 		$pageCode = 'index';
	 	
	 	$pageData = Model_Page::getInstance()->getByCode($pageCode);
	 	
	 	if(empty($pageData) || $pageData['published']==false)
	 	{
	 		$pageData = Model_Page::getInstance()->getByCode($pageCode);
	 		if(empty($pageData))
	 			trigger_error('Ivalid site structure' , E_USER_ERROR); 	 					 		
	 	}

	 	$page = Page::getInstance();
	 	
	 	foreach($pageData as $k=>$v)
	 		$page->$k = $v;

	 	if($page->show_blocks){
	 		$blockManager = Blockmanager::getInstance();
	 		$blockManager->init($page->id);
	 	}	
	 		
	 	/**
	 	 * Check if controller attached
	 	 */
	 	if(strlen($page->func_code)){
	 		$fModules = Config::factory(Config::File_Array, Application::getConfig()->get('frontend_modules'));
	 		if($fModules->offsetExists($page->func_code)){
	 			$controllerConfig = $fModules->get($page->func_code);
	 			$controller = new $controllerConfig['class']();
	 			$controller->run();
	 		}
	 	} 	
	 	
	 	$page->show();
	 }

	 static protected function _getModulesRoutes()
	 {
	 	self::$_moduleRoutes = array();
	 	
	 	$cache = Application::dataCache();
	 	if(!$cache || !$list = $cache->load(self::CACHE_KEY_ROUTES)){
	 		$pageModel = Model_Page::getInstance();
	 		$db = Application::getDbConnection();
	 		$sql = $db->select()
	 				  ->from($pageModel->table() , array('code','func_code'))
	 				  ->where('`published` = 1')
	 				  ->where('`func_code` !="" ');
	 	    $list = $db->fetchAll($sql);
	 	    if($cache)
	 	    	$cache->save($list , self::CACHE_KEY_ROUTES);
	 	}
	 	
	 	if(!empty($list)){
		 	foreach ($list as $item)
		 		self::$_moduleRoutes[$item['func_code']] = $item['code'];
	 	}else{
	 		self::$_moduleRoutes = array();
	 	}
	 }
	 /**
	  * Find url path for module
	  * @param string $module
	  * @throws Exception
	  * @return string
	  */
	 static public function findUrl($module)
	 {	 	
	 	if(is_null(self::$_moduleRoutes))
	 		self::_getModulesRoutes();
	 	 	 	
	 	if(!array_key_exists($module, self::$_moduleRoutes))
	 		throw new Exception('Invalid module code ' . $module);
	 		
	 	return self::$_moduleRoutes[$module];
	 	
	 }
}